package com.book.core.mode;

import com.alibaba.fastjson.annotation.JSONField;
import com.book.core.domain.SysUser;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@ToString
public class SysLoginUser implements UserDetails {
    private SysUser sysUser;
    private List<String> roles;
    private List<String> menus;

    public SysLoginUser(SysUser sysUser) {
        this.sysUser = sysUser;
    }

    public SysLoginUser() {
    }

    public SysLoginUser(SysUser sysUser, List<String> roles, List<String> menus) {
        this.sysUser = sysUser;
        this.roles = roles;
        this.menus = menus;
    }

    /**权限列表
     * @return {@link Collection }<{@link ? } {@link extends } {@link GrantedAuthority }>
     */
    @Override
    @JSONField(serialize = false)
    public Collection<? extends GrantedAuthority> getAuthorities() {
//        return menus.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        // 合并菜单权限和角色
        List<String> combined = new ArrayList<>();
        if (menus != null) combined.addAll(menus);
        if (roles != null) {
            // 为角色添加ROLE_前缀（Spring Security规范）
            combined.addAll(roles.stream()
                    .map(role -> "ROLE_" + role)
                    .collect(Collectors.toList()));
        }
        return combined.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        return sysUser.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
